package servidor.principal.control;


import comun.*;
import comun.dto.*;
import comun.iControl.*;



import java.rmi.server.UnicastRemoteObject;
import java.util.*; 

import servidor.principal.assembler.ClienteAssembler;
import servidor.dominio.Cliente;


import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Extent;
import javax.jdo.Query; 
import javax.jdo.JDOHelper;
import javax.jdo.Transaction;
import servidor.dominio.*; 



public class ControlCliente extends UnicastRemoteObject implements IControlCliente{



	public ControlCliente() throws Exception{ 
	}
	
	public boolean addClienteDTO(ClienteDTO pDTO) throws Exception {

		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		
		Cliente p = ClienteAssembler.getCliente(pDTO);
			try{
			//	this.persistencia.AbreTrans();
				tx.begin();
				pm.makePersistent(p);
				tx.commit();
				//this.persistencia.cargarObjetoPersistente(p);
				//this.persistencia.cierraTrans();
				System.out.println("Cliente dado de alta. OK");

			}
			finally
			{
				if (tx.isActive())
				{
					tx.rollback();
				}
				pm.close();
			} 
			return true;
	}
	


	public Vector<ClienteDTO> getClientes(String nombre) throws Exception {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();
		tx.begin();
		
	
		Vector<ClienteDTO> vector = new Vector<ClienteDTO>();
		Collection<Cliente> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			String filter = "nombre == \""+nombre+"\"";
			consultaCol= this.getObjects(pm,Cliente.class,filter);
			Iterator<Cliente> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Cliente client = iter.next();
				ClienteDTO clientDTO = ClienteAssembler.getClienteDTO(client);
				vector.add(clientDTO);
			}           
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}
		return vector;
	}


	public Vector<ClienteDTO> getClientes() throws Exception {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		Vector<ClienteDTO> vector = new Vector<ClienteDTO>();
		Collection<Cliente> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			consultaCol= this.getObjects(pm,Cliente.class,null);
			Iterator<Cliente> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Cliente client = iter.next();
				ClienteDTO clientDTO = ClienteAssembler.getClienteDTO(client);
				vector.add(clientDTO);
			}            
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}
		return vector;
	}

	public Vector<ClienteDTO> getClientesCuit(String cuit) throws Exception {
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		Vector<ClienteDTO> vector = new Vector<ClienteDTO>();
		Collection<Cliente> consultaCol = null;       

		try {
			if (!tx.isActive())tx.begin();
			String filter = "cuit == \""+cuit+"\"";
			consultaCol= this.getObjects(pm,Cliente.class,filter);
			Iterator<Cliente> iter = consultaCol.iterator();
			while (iter.hasNext()) {
				Cliente client = iter.next();
				ClienteDTO clientDTO = ClienteAssembler.getClienteDTO(client);
				vector.add(clientDTO);
			}            
			tx.commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) tx.rollback();
		}
		return vector;
	}
	



	public boolean existeCliente(String cuit) throws Exception {

		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		boolean existe = false;
		try {

			if (!tx.isActive())tx.begin();
			String filter = "cuit == \""+cuit+"\"";
			Collection clienteCol= this.getObjects(pm,Cliente.class,filter);
			if (clienteCol.size()==1) 
				existe=true;

			try {
				tx.commit(); 
			} catch (RuntimeException e) {
				e.printStackTrace();
				return false;
			}
		} finally {


			if (tx.isActive()) tx.rollback();
		}
		return existe;

	} 

	public boolean existeClienteNombre(String nombre) throws Exception {

		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		tx = pm.currentTransaction();

		boolean existe = false;
		try {

			if (!tx.isActive())tx.begin();
			String filter = "nombre == \""+nombre+"\"";
			Collection clienteCol= this.getObjects(pm,Cliente.class,filter);
			if (clienteCol.size()>=1) 
				existe=true;

			try {
				tx.commit(); 
			} catch (RuntimeException e) {
				e.printStackTrace();
				return false;
			}
		} finally {


			if (tx.isActive()) tx.rollback();
		}
		return existe;

	} 

	public void eliminarCliente(String cuit) throws Exception{

		//VER ACA EL ELIMINAR YO VOY A TENER QUE ELIMINAR LOS LIBROS LAS ACTIVIDADES Y ALGO MAS JE
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		try {
			tx.begin();
			if (!tx.isActive())tx.begin();   
			Cliente cliente = new Cliente();
			String filter = "cuit == \""+cuit+"\"";
			Collection clienteCol= this.getObjects(pm,Cliente.class,filter);

			Iterator<Cliente> iter = clienteCol.iterator();
			while (iter.hasNext()) {
				Cliente client = iter.next();
				ClienteDTO clientDTO = ClienteAssembler.getClienteDTO(client);
				pm.deletePersistent(client);
				//vector.add(clientDTO);
			}           
			/*
			    //Elimino la cta. cte.
				CuentaCorriente cta = cliente.getCuentaCorriente();
				Collection m = cta.getMovimientos();

				for (Iterator i = m.iterator(); i.hasNext(); ) {
					Movimiento movimiento = (Movimiento)i.next();
					this.persistencia.borrarObjeto(movimiento);
				}

				this.persistencia.borrarObjeto(cta);

				//Elimino las empresas
				Collection empresas = cliente.getEmpresas();
				for (Iterator i = empresas.iterator(); i.hasNext(); ) {
						Empresa empresa = (Empresa)i.next();

		                //Elimino el Plan de Cuenta
						PlanDeCuenta plan = empresa.getPlan();
						eliminarCuentas(plan.getCodigoEmpresa());
						this.persistencia.borrarObjeto(plan);

						//Elimino el Libro Diario
						LibroDiario diario = empresa.getLibroDiario();
						eliminarRegistros(diario.getCodigoEmpresa());
						this.persistencia.borrarObjeto(diario);

						this.persistencia.borrarObjeto(empresa);
				}*/

			//pm.deletePersistent(cliente);
			tx.commit();
			System.out.println("Cliente Eliminado. OK");

			//this.persistencia.borrarObjeto(cliente);
			//this.persistencia.cierraTrans();


		}	
		finally
		{
			if (tx.isActive())
			{
				tx.rollback();
			}
			pm.close();
		} 
	}


	public void modificarCliente(ClienteDTO c) throws Exception{
		PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory("jpox.properties");
		PersistenceManager pm = pmf.getPersistenceManager();
		Transaction tx=pm.currentTransaction();
		try {
			//this.persistencia.AbreTrans();
			tx.begin();
			if (!tx.isActive())tx.begin(); 
			String filter = "cuit == \""+c.getCuit()+"\"";
			Cliente cliente= (Cliente)this.getObject(pm,Cliente.class,filter);
			cliente.setDomicilio(c.getDomicilio());
			cliente.setCondIva(c.getCondIva());
			cliente.setNombre(c.getNombre());
			cliente.setLocalidad(c.getLocalidad());
			cliente.setTelefono(c.getTelefono());
			cliente.setesCliente(c.getesCliente());
			cliente.setNroIngBruto(c.getNroIngBruto());

			tx.commit();
			System.out.println("Cliente Modificado. OK");

		}	
		finally
		{
			if (tx.isActive())
			{
				tx.rollback();
			}
			pm.close();
		} 
	}


	
	public Collection getObjects(PersistenceManager pm, Class clase,String filter)throws Exception{
		Collection retorno=null;
		try{
			Class clienteClass = clase;
			Extent clnCliente=pm.getExtent(clienteClass, false);
			Query query = pm.newQuery(clnCliente,filter);
			retorno=(Collection)query.execute();
		} catch(Exception e) {
			throw e;
		}
		return retorno;
	}

	private Collection getObjects(PersistenceManager pm, Class clase)throws Exception{
		Collection retorno=null;
		try{
			Class clienteClass = clase;
			Extent clnCliente = pm.getExtent(clienteClass, false);
			Query query = pm.newQuery(clnCliente);
			retorno=(Collection)query.execute();
		} catch(Exception e) {
			throw e;
		}
		return retorno;
	}


	public Object getObject(PersistenceManager pm,Class clase,String filter) throws Exception{
		Object objetoPersistente = null;
		try {

			Extent clnObject = pm.getExtent(clase, true);
			Query query = pm.newQuery(clnObject,filter);
			Collection objetos = (Collection)query.execute();


			Object[] prueba = objetos.toArray();
			if(prueba.length > 0){
				objetoPersistente = prueba[0];
			}	
		}
		catch (Exception ex) {
			ex.printStackTrace();
			throw ex;           
		}
		return objetoPersistente;
	}







}
